/*
 * Copyright Aristool AG Switzerland
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); 
 * you may not use this file except in compliance with the License. 
 * You may obtain a copy of the License at 
 * 
 * http://www.apache.org/licenses/LICENSE-2.0 
 * 
 * Unless required by applicable law or agreed to in writing, software 
 * distributed under the License is distributed on an "AS IS" BASIS, 
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
 * See the License for the specific language governing permissions and 
 * limitations under the License.
 */
package org.opprua.tidy.gens;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.opprua.tidy.util.CodePrint;

/**
 * TODO: add Java doc
 *
 * Prepared for first commit: 15.04.2007
 *
 * @author Lin Li
 */
public class GIf extends Gtor {

  private static class Alter {
    public String expression;
    public GState statements;
    
    public Alter(String ex) {
      expression = ex;
      statements = new GState();
    }
  }

  private List<Alter> alts = new ArrayList<Alter>();
  
  /**
   * <p>Constructor for an if statement generator</p>
   */
  public GIf() {
  }

  /**
   * <p>Add a condition for the if statement.</p>
   *  
   * @param expression the expression for the condition in the if clause
   * @return the statement generator for execution when the condition is true
   */
  public GState addCondition(String expression) {
    Alter a = new Alter(expression);
    alts.add(a);
    return a.statements;
  }

  /**
   * <p>Add a condition for the if statement together with the execution
   * code for that condition.</p>
   * 
   * @param expression for the condition in the if clause
   * @param statement the statement for execution
   */
  public GIf addCondition(String expression, String statement) {
    addCondition(expression).addStatement(statement);
    return this;
  }
  
  /**
   * <p>dump the statement into the file.</p>
   */
  public void dump(CodePrint w) {

    if ( alts.size() == 0 ) {
      return;
    }

    blockComments(w);
    
    boolean started = false;
    for (Iterator<Alter> iter = alts.iterator(); iter.hasNext();) {
      Alter a = iter.next();
      if ( started ) {
        w.print(" else ");
      } 
      if ( a.expression != null && a.expression.trim().length() > 0) {
        w.print("if ("+a.expression.trim()+") ");
      }
      a.statements.dump(w);
      started = true;
    }  
  }
}
